<template>
    <div class="main">
        <div class="login_box">
            <div class="title">
                欢迎登录自动化运维平台
            </div>
            <el-divider border-style="double" />
            <div class="login_form">
                <el-form :model="form" ref="form" :rules="rules" label-width="20px">
                    <el-form-item prop="username">
                      <el-input class="el-input" v-model="form.username" placeholder="用户名" :prefix-icon="User" />
                    </el-form-item>
                    <el-form-item prop="password">
                      <el-input class="el-input" v-model="form.password" placeholder="密码" :prefix-icon="Lock" type="password" show-password />
                    </el-form-item>
                    <el-form-item prop="code">
                      <el-input style="width: 280px;" class="el-input" v-model="form.code" placeholder="验证码" :prefix-icon="CircleCheck" />
                      <div style="cursor: pointer;margin-left: 30px;" @click="refreshCode"><s-identify :identifyCode="identifyCode"></s-identify></div>
                    </el-form-item>
                </el-form>
               <el-checkbox v-model="form.rememberMe" style="margin-left: 22px;">记住密码</el-checkbox>
                <el-form-item >
                  <el-button type="primary"  @click="onSubmit" @keyup.enter="keyDown">登&nbsp&nbsp&nbsp&nbsp录</el-button>
                </el-form-item>
            </div>
        </div>
    </div>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2024 阿哲 <a style="text-decoration: none;color: #FFFFFF" href="https://www.azhe.xin" target="_blank">www.azhe.xin</a></span>
    </div>
</template>

<script>
    //验证码组件
    import SIdentify from "../components/SIdentify.vue";
    import {ElMessage} from "element-plus";

    import {User, Lock, CircleCheck} from "@element-plus/icons-vue";
    import { ElNotification } from 'element-plus'
    //记住密码
    import Cookies from "js-cookie";
    import { encrypt, decrypt } from "@/util/jsencrypt";
    export default {
        name: "Login",
        //注册组件
        components: { SIdentify },
        data() {
            return {
                form: {
                    username: '',
                    password: '',
                    code: '',
                    rememberMe: false,
                },
                identifyCode: '',
                identifyCodes: '1234567890abcdefjhijklinopqrsduvwxyz', //验证码出现的数字和字母
                rules: {
                    username: [
                        {required: true, message: '请输入用户名', trigger: 'blur'},
                        {min: 3, message: '用户名长度应不小于3个字符', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 6, message: '密码长度应不小于6个字符', trigger: 'blur'}
                    ],
                    code: [
                        {required: true, message: '请输入验证码', trigger: 'blur'},
                        {min: 4, message: '验证码长度应不小于4个字符', trigger: 'blur'}
                    ]
                }
            }
        },
        methods: {
          refreshCode() {
            this.identifyCode = '';
            this.makeCode(this.identifyCodes, 4);
          },
          makeCode(o, l) {
            for (let i = 0; i < l; i++) {
                this.identifyCode += this.identifyCodes[
                    this.randomNum(0, this.identifyCodes.length)]
            }
            console.log(this.identifyCode);
          },
          randomNum(min, max) {
              return Math.floor(Math.random() * (max - min) + min);
          },
          keyDown(e){
            //如果是回车则执行登录方法
            if(e.keyCode === 13){
                //需要执行的登录方法
               this.onSubmit();
            }
          },
          onSubmit() {
              // 提交前预验证
              this.$refs.form.validate((valid) => {  //回调函数中valid布尔值
                  if (valid) {
                       //验证验证码是否正确
                       if (this.identifyCode !== this.form.code) {
                            this.form.code = '';
                            this.refreshCode();
                            ElMessage({
                                message: "验证码错误！",
                                type: 'error',
                            })
                            return;
                        }
                        this.$http.post('/login/', this.form)
                            .then(res=> {
                                if (res.data.code == 200) {
                                    // 保存token到会话存储
                                    window.localStorage.setItem('token', res.data.token);
                                    window.localStorage.setItem('username', res.data.username);
                                    window.localStorage.setItem('role', res.data.role);
                                    window.localStorage.setItem('first_name', res.data.first_name);
                                    //首次登录判断是否有头像，如果没有使用默认头像
                                    if(res.data.avatar){
                                         window.localStorage.setItem('userAvatar', res.data.avatar);
                                    }
                                     // 勾选了需要记住密码在cookie中设置用户名和密码
                                    if (this.form.rememberMe) {
                                        Cookies.set("username", this.form.username, { expires: 7 });
                                        Cookies.set("password", encrypt(this.form.password), { expires: 7 });
                                        Cookies.set("rememberMe", this.form.rememberMe, { expires: 7 });
                                      } else {
                                      // 否则移除
                                        Cookies.remove("username");
                                        Cookies.remove("password");
                                        Cookies.remove("rememberMe");
                                      }
                                    this.$router.push("/dashboard"); //站内跳转，跳转到首页
                                    this.$message.success('登录成功')
                                    const first_name = window.localStorage.getItem('first_name')
                                    ElNotification({
                                        title: '登录成功',
                                        message: `欢迎回来, ${first_name}！`,
                                        type: 'success',
                                     })
                                }
                            })
                            .catch((error)=>{
                                // this.$message.warning('用户名或密码错误！')
                            })
                  } else {
                      // this.$message.warning('用户名或密码格式错误！')
                  }
              })
          },
          //进入登录页面获取cookies中设置的用户名密码，如果没有则为空
          getCookie() {
              const username = Cookies.get("username");
              const password = Cookies.get("password");
              const rememberMe = Cookies.get("rememberMe");
              this.form = {
                  username: username === undefined ? this.form.username : username,
                  password: password === undefined ? this.form.password : decrypt(password),
                  rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
              };
           }
        },
        mounted() {
          //获取cookies中的用户名密码
          this.getCookie();
          //刷新验证码
          this.identifyCode = "";
          this.makeCode(this.identifyCodes, 4);
          //回车事件
          window.addEventListener('keydown', this.keyDown);
        },
        unmounted() {
          window.removeEventListener('keydown', this.keyDown);
        },
      setup() {
            return {
                User, Lock, CircleCheck
            }
        },
    }
</script>

<style scoped>
    .main {
        background-image: url("../assets/img/login-background.jpg");
        background-size: 100% 100%;
        height: 100%;
    }
    .login_box {
        width: 500px;
        height: 395px;
        background: white;
        border-radius: 10px;
        /*box-shadow: 0 5px 20px 0 #f5f5f5;*/
        position: absolute;
        top: 0;
        bottom: 0px;
        right: 0px;
        left: 0px;
        margin: auto;
    }
    .title {
        font-size: 20px;
        font-weight: bold;
        color: dodgerblue;
        text-align: center;
        margin-top: 20px;
    }
    .login_form {
        width: 450px;
        margin-top: 30px;
        margin-left: 15px;
    }
    .el-input {
       height: 40px;
    }
    .login_form .el-button {
        margin-top: 20px;
        margin-left: 20px;
        width: 450px;
        height: 40px;
    }
    .el-login-footer {
      height: 40px;
      line-height: 40px;
      position: fixed;
      bottom: 0;
      width: 100%;
      text-align: center;
      color: #fff;
      font-family: Arial;
      font-size: 12px;
      letter-spacing: 1px;
    }
</style>